import { defineStore } from 'pinia'
import { RouteLocationNormalized } from 'vue-router'
import useCachedRouteStore from '@/store/modules/cached-routes'
import { findCachedRoutes } from '../help'
import pinia from '../pinia'

// 持久化
// const visitedRoutes = JSON.parse(localStorage.getItem('visited-routes') || '[]')

const useVisitedRouteStore = defineStore('visited-routes', {
  state: () => {
    return {
      // 记录顶部菜单
      rootMenu: '/index',
      // 发起页面参数
      originator: undefined,
      visitedRoutes: [] as RouteLocationNormalized[],
      isLoadAffix: false, // 是否已加载
    }
  },
  getters: {
    getVisitedRoutes(state) {
      return state.visitedRoutes
    },
  },
  actions: {
    initAffixRoutes(affixRoutes: RouteLocationNormalized[]) {
      affixRoutes.reverse().forEach((affixRoute) => {
        if (!this.visitedRoutes.find((it) => it.fullPath === affixRoute.fullPath)) {
          this.visitedRoutes.unshift(affixRoute)
        }
      })
      this.isLoadAffix = true
    },
    addVisitedRoute(route: RouteLocationNormalized, from: RouteLocationNormalized) {
      return new Promise((resolve) => {
        if (this.originator) {
          route.meta.originator = this.originator
          if (this.originator.title) {
            route.meta.title = this.originator.title
          }
          this.originator = undefined
        }
        // visited_tab中是否存在
        const alive_tab = this.visitedRoutes.find((it) => it.path === route.path)
        if (alive_tab) {
          alive_tab.fullPath = route.fullPath
        } else {
          // 没找到，去增加
          // 页面keep-alive begin
          if (route.name && route.meta.cacheable !== false) {
            const cachedRoutesStore = useCachedRouteStore()
            const routeName = (route.name as string)
            if (!cachedRoutesStore.cachedRoutes.includes(routeName)) {
              cachedRoutesStore.cachedRoutes.push(routeName)
            }
          }
          // 页面keep-alive end
          // 创建顶部访问标签 并插入到当前tab后面 begin
          const selectedMenu = from.fullPath
          const index = this.visitedRoutes.findIndex((it) => it.fullPath === selectedMenu)
          if (index != -1) {
            this.visitedRoutes.splice(index + 1, 0, route)
          } else {
            this.visitedRoutes.push(route)
          }
          // end
        }
        resolve(route)
      })
    },
    removeVisitedRoute(route: RouteLocationNormalized) {
      return new Promise<string>((resolve) => {
        this.visitedRoutes.splice(this.visitedRoutes.indexOf(route), 1)
        if (route.name) {
          const route_name = (route.name as string)
          const cachedRoutesStore = useCachedRouteStore()
          if (cachedRoutesStore.cachedRoutes.includes(route_name)) {
            cachedRoutesStore.cachedRoutes.splice(cachedRoutesStore.cachedRoutes.indexOf(route_name), 1)
          }
        }
        // this.persistentVisitedView()
        resolve(this.findLastRoutePath())
      })
    },
    findLastRoutePath() {
      return this.visitedRoutes && this.visitedRoutes.length > 0 ? this.visitedRoutes[this.visitedRoutes.length - 1].fullPath : '/'
    },
    closeLeftVisitedView(selectRoute: RouteLocationNormalized) {
      return new Promise((resolve) => {
        const selectIndex = this.visitedRoutes.indexOf(selectRoute)
        if (selectIndex !== -1) {
          this.visitedRoutes = this.visitedRoutes.filter((it, index) => {
            return (it.meta && it.meta.affix) || index >= selectIndex
          })
          const cachedRoutesStore = useCachedRouteStore()
          cachedRoutesStore.setCachedRoutes(findCachedRoutes(this.visitedRoutes))
          // this.persistentVisitedView()
        }
        resolve(selectRoute)
      })
    },
    closeRightVisitedView(selectRoute: RouteLocationNormalized) {
      return new Promise((resolve) => {
        const selectIndex = this.visitedRoutes.indexOf(selectRoute)
        if (selectIndex !== -1) {
          this.visitedRoutes = this.visitedRoutes.filter((it, index) => {
            return (it.meta && it.meta.affix) || index <= selectIndex
          })
          const cachedRoutesStore = useCachedRouteStore()
          cachedRoutesStore.setCachedRoutes(findCachedRoutes(this.visitedRoutes))
          // this.persistentVisitedView()
        }
        resolve(selectRoute)
      })
    },
    closeAllVisitedView() {
      return new Promise<void>((resolve) => {
        this.visitedRoutes = this.visitedRoutes.filter((it) => {
          return it.meta && it.meta.affix
        })
        const cachedRoutesStore = useCachedRouteStore()
        cachedRoutesStore.setCachedRoutes(findCachedRoutes(this.visitedRoutes))
        // this.persistentVisitedView()
        resolve()
      })
    },
    closeOtherVisitedView(fullPath: string) {
      return new Promise<void>((resolve) => {
        this.visitedRoutes = this.visitedRoutes.filter((it) => {
          return (it.meta && it.meta.affix) || it.fullPath == fullPath
        })
        const cachedRoutesStore = useCachedRouteStore()
        const cachedRoutes: string[] = []
        this.visitedRoutes.forEach((it: any) => {
          const pageName = (it.name as string)
          cachedRoutes.push(pageName)
        })
        cachedRoutesStore.setCachedRoutes(cachedRoutes)
        // this.persistentVisitedView()
        resolve()
      })
    },
    // 关闭一个
    closeItemVisitedView(fullPath: string) {
      return new Promise<void>((resolve) => {
        const delIndex = this.visitedRoutes.findIndex((it) => it.fullPath == fullPath)
        const route = this.visitedRoutes[delIndex]
        this.visitedRoutes.splice(delIndex, 1)

        // 删除keep-alive cache
        if (!route) return
        const pageName = (route.name as string)
        const cachedRoutesStore = useCachedRouteStore()
        const delIndex1 = cachedRoutesStore.cachedRoutes.findIndex((it) => it == pageName)
        // 判断当前 visitedRoutes 中是否还有和当前route同样 route.name 的页面
        // 比如：还车页，在打开多个还车页的情况下，关闭一个还车页面，此时不能删除 cachedRoutes
        const existSameVisitedTab = this.visitedRoutes.some((it: any) => {
          const _pageName = (it.name as string)
          return _pageName == pageName
        })
        // 不存在相同名称 cacheRoute，允许删除
        if (!existSameVisitedTab) cachedRoutesStore.cachedRoutes.splice(delIndex1, 1)
        // this.persistentVisitedView()
        resolve()
      })
    },
    // 持久化
    persistentVisitedView() {
      const tempPersistendRoutes = this.visitedRoutes.map((it) => {
        return {
          fullPath: it.fullPath,
          meta: it.meta,
          name: it.name,
          path: it.path,
          backPath: it.backPath,
        }
      })
      localStorage.setItem(this.$id, JSON.stringify(tempPersistendRoutes))
    },
    restoreVisitedView() {
      this.$reset()
    },
  },
  // 由于需要自定义持久化过程，所以这里就不能用插件来实现
  // presist: {
  //   enable: true,
  // },
})

export function useVisitedRoutesContext() {
  return useVisitedRouteStore(pinia)
}

export default useVisitedRouteStore
